<?php
// $Id$

/**
 * Controller_Pay 控制器
 */
class Controller_Pay extends Controller_Abstract
{
	function actionIndex()
	{
			
	}
	/**
	 *
	 * 订单发货
	 */
	function actionDispatch()
	{
		$orderid = trim($this->_context->oid);
		if (!helper_users_login::is_login())
		{
			return $this->_redirectMessage('出错啦!', '只有登录后才可以查看自己的订单卡密信息', url('default'));
		}
		if ($orderid)
		{
			$order = Orders::find('orderid = ? and target_userid = ?',$orderid,$_SESSION[helper_users_login::$_Login_SessionKey]['userid'])->getOne();
			if ($order->id())
			{
				switch ($order->orderstatus)
				{
					case 1:
						return $this->_redirectMessage('出错啦!', '订单未支付不能提卡!', url('default'));
						break;
					case 2:// 可以提卡
						if (Productcard::find('orderid = ? and status=1',$order->orderid)->getCount())
						{
							// 已经提取过了.
							// 修改状态
							$order->changeProps(array('orderstatus'=>3));
							$order->save();
						}else{
							// 取卡
							$card = Productcard::find('status=0 and p_code = ?',$order->p_code)->order('createtime asc')->getOne();
							if ($card->id())
							{
								// 有卡
								// 绑定卡号
								$card->changeProps(array(
										'orderid'=>$order->orderid,
										'gettime'=>time(),
										'userid'=>$order->target_userid,
										'status'=>1
									));
								$card->save();
								// 修改状态
								$order->changeProps(array('orderstatus'=>3));
								$order->save();
							}else{
								// no库存
								return $this->_redirectMessage('出错啦!', '此产品卡号库存不足,请联系客服人员!', url('default'));
							}
						}
						$this->_view['order'] = $order;
						break;
					case 0:
					case 3:
						$this->_view['order'] = $order;
						break;
					case 999:
					default:
						return $this->_redirectMessage('出错啦!', '订单信息已被取消!', url('default'));
						break;
				}
			}else {
				return $this->_redirectMessage('出错啦!', '订单信息不存在或此订单不是您下的订单!', url('default'));
			}
		}else{
			return $this->_redirect(url('default'));
		}
	}
}